import wechath5 from "@/utils/wechath5";
import Cache from "@/utils/cache";
import {
	isWeixinClient,
	toast
} from "@/utils/tools";
import {
	baseURL,
	basePath
} from "@/config/app";
import {
	getGeocoder,
	getNearbyShops
} from "@/api/store.js";
import {
	SHOP_CODE,
	BACK_URL
} from "@/config/cachekey";

const state = {
	cityInfo: {
		// id: city_id,
		// name: result.ad_info.city,
		// gcj02_lat: result.location.lat,
		// gcj02_lng: result.location.lng
	},
	locationInfo: null,
};

const mutations = {
	setCityInfo(state, data) {
		state.cityInfo = data;
		uni.$emit("refreshhome");
	},
	setLocationInfo(state, data) {
		state.locationInfo = data;
		uni.$emit("refreshhome");
	},
};

const actions = {
	// 位置授权
	async getAuthorize({
		dispatch
	}) {
		const [error, data] = await uni.showModal({
			title: "您已拒绝地理位置权限",
			content: "是否进入权限管理，调整授权？",
		});
		if (data.confirm) {
			const [error, data] = await uni.openSetting();
			if (data.authSetting["scope.userLocation"]) dispatch("initLocationFunc");
		}
	},
	// 获取当前经纬度
	async getLocationFunc({
		dispatch,
		rootState,
		commit
	}) {
		console.log("获取地址");
		try {
			uni.showLoading({
				title: '获取定位中...',
				mask: true
			})
			const [error, res] = await uni.getLocation({
				// #ifndef APP
				type: "gcj02",
				// #endif
			});
			// #ifdef MP
			dispatch("getSystemInfo");
			if (!rootState.app.sysInfo.locationEnabled) {
				toast({
					title: "您的手机定位还未开启，获取位置失败！"
				});
			}
			// #endif
			// #ifdef MP
			// if (!res) return dispatch("getAuthorize");
			// #endif
			uni.hideLoading();
			if (error) {
				toast({
					title: "获取位置失败"
				});
			}
			// #ifdef APP-PLUS

			if (!res) return toast({
				title: "获取位置失败"
			});
			// #endif
			let locationObj = !res ? null : {
				longitude: res.longitude,
				latitude: res.latitude
			}
			commit("setLocationInfo", locationObj);

			dispatch("getGeocoderFunc", locationObj);
		} catch (err) {
			console.log(err);
			// toast({ title: err.errMsg })
			// throw new Error(err + '获取位置')
		}
	},
	// 获取当前定位
	async initLocationFunc({
		dispatch,
		rootState
	}) {
		console.log("获取地址");
		try {
			uni.showLoading({
				title: '获取定位中...',
				mask: true
			})
			const [error, res] = await uni.getLocation({
				// #ifndef APP
				type: "gcj02",
				// #endif
			});
			console.log(error, res, "----");
			// if(error?.errMsg == 'getLocation:fail 频繁调用会增加电量损耗，可考虑使用 wx.onLocationChange 监听地理位置变化') return toast({ title: '频繁定位，请稍后' })
			// #ifdef MP
			dispatch("getSystemInfo");
			if (!rootState.app.sysInfo.locationEnabled) {
				uni.showModal({
					title: "温馨提示",
					content: "您的手机定位还未开启，请手动选择门店进入",
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							const pages = getCurrentPages();
							const page = Cache.get(BACK_URL) ? Cache.get(BACK_URL) : pages[pages
								.length - 1].$page.fullPath;
							uni.setStorageSync("shop_street_return_url", decodeURIComponent(page));
							uni.navigateTo({
								url: '/pages/shop_street/shop_street',
							})
						}
					}

				});
				return;
			}
			// #endif
			// #ifdef MP
			// if (!res) return dispatch("getAuthorize");
			// #endif
			uni.hideLoading();
			if (error) {
				uni.showModal({
					title: "温馨提示",
					// content: JSON.stringify(error.errMsg)
					content: "获取位置失败，请手动选择门店进入！",
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							const pages = getCurrentPages();
							const page = Cache.get(BACK_URL) ? Cache.get(BACK_URL) : pages[pages
								.length - 1].$page.fullPath;
							uni.setStorageSync("shop_street_return_url", decodeURIComponent(page));
							uni.navigateTo({
								url: '/pages/shop_street/shop_street',
							})
						}
					}
				});
				return;
			}
			// #ifdef APP-PLUS

			if (!res) return toast({
				title: "获取位置失败，请选择门店"
			}, {
				tab: 2,
				url: '/pages/shop_street/shop_street'
			})
			// #endif
			dispatch("getGeocoderFunc", {
				longitude: res.longitude,
				latitude: res.latitude
			});
		} catch (err) {
			console.log(err);
			// toast({ title: err.errMsg })
			// throw new Error(err + '获取位置')
		}
	},
	// 逆解析地址
	getGeocoderFunc({
		commit
	}, location) {
		console.log(location);
		getNearbyShops({
			...location
		}).then((res) => {
			if (res.code == 1) {
				const id = res.data[0].id;
				Cache.set(SHOP_CODE, id);
			} else {
				toast({
					title: res.msg
				});
			}
			uni.$emit("refreshhome");
		});
	},
};

export default {
	state,
	mutations,
	actions,
};